<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <style type="text/css">
        .add-file-warp {
            margin-bottom: 100px;
        }

        .input-item {
            padding-bottom: 20px;
            padding-top: 30px;
            border-bottom: 1px solid gold;
        }
        .file-item-del{
            margin-left: 30px;
            color: red;
            cursor:pointer;
        }
    </style>

    <!--jquery-->
    <script src="./plugins/jquery-3.4.1.min.js"></script>

</head>

<body>
    <div id="file_upload_demo">
        <div class="add-file-warp">
            <button class="add-input-file">添加</button>
        </div>


        <div class="input-list">
            <!--<div class="input-item">
                <input class="input-file-item" type="file" id="file1" onchange="inputChangeHander">
            </div>-->
        </div>
    </div>
</body>
<script>
    $(function () {
        var namespace = 'file_upload_demo';


        // 存放全局数据
        var _app_data_ = {
            fileList: [createFile(false)]
        }
        // 当前上传文件
        var currFileId = 1

        // 调用初始化文件
        init()

        // 初始化渲染一个上传input
        function init() {
            if (_app_data_.fileList.length && _app_data_.fileList.length > 0) {
                _app_data_.fileList.forEach((file, ix) => {
                    // let ix = randomNum(10000, 99999)
                    addInput(file, ix)
                })
            }
        }

        // 动态增加input
        function addInput(file, ix) {
            let htmlStr = `<div class="input-item" id="inputitem${file.uid}" ix="${ix}">
<span>${file.label}: </span>
<input class="input-file-item" type="file" id="file${file.uid}" />
${file.isDel? '<span class="file-item-del" id="filedel'+file.uid+'">删除</span>': ''}
</div>`
            $('.input-list').append(htmlStr)
            $('#file' + file.uid).change(() => {
                currFileId = file.uid
                console.log('currFileId : ',currFileId)
                console.log('change', '#file' + file.uid);
                upload2('file' + file.uid)
            })
            if (file.isDel) {
                console.log('#filedel' + file.uid, file.isDel);
                $('#filedel' + file.uid).on('click', () => {
                    let removeId = 'inputitem' + file.uid
                    console.log('#filedel=============click' + file.uid, removeId);
                    let ix = $('#' + removeId).attr('ix')
                    $('#' + removeId).remove()
                    _app_data_.fileList.splice(Number(ix), 1)
                })
            }
        }

        // 增加按钮点击事件
        $('.add-input-file').on('click', () => {
            let file = createFile(true);
            _app_data_.fileList.push(file)
            addInput(file, _app_data_.fileList.length - 1)
        })

        // 创建fileList一个对象
        function createFile(flag) {
            let uid = randomNum(10000, 99999);
            let file = {
                uid: uid,
                label: '文件' + uid,
                name: 'file' + uid,
                value: '',
                isDel: flag
            }
            return file;
        }

        function upload2(fileInput) {
            var fileObj = document.getElementById(fileInput).files[0]; // js 获取文件对象

// CFF 上传的接口失败了。为啥？！

            var url = "/common/upload"; // 接收上传文件的后台地址

            var form = new FormData(); // FormData 对象

            form.append("file", fileObj); // 文件对象

            xhr = new XMLHttpRequest(); // XMLHttpRequest 对象

            xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。

            xhr.onload = uploadComplete; //请求完成

            xhr.onerror = uploadFailed; //请求失败

            // xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】

            xhr.upload.onloadstart = function(){//上传开始执行方法

                ot = new Date().getTime(); //设置上传开始时间

                oloaded = 0;//设置上传开始时，以上传的文件大小为0

            };

            xhr.send(form); //开始上传，发送form数据

        }

        //上传成功响应
        function uploadComplete(evt) {
            //服务断接收完文件返回的结果
            var data = JSON.parse(evt.target.responseText);
            console.log(data);
            if(data.code == 200) {
                // console.log(currFileId);
                _app_data_.fileList.forEach((f,i) => {
                    if (f.uid == currFileId) {
                        f.value = data.url;
                    }
                })
                let itemId = 'inputitem' + currFileId
                console.log('itemId', itemId)
                $('#' + itemId).append(`<img width="50" height="50"  src="${data.url}"/>`)
                // alert("上传成功！=> " + data.url);
            }else{undefined
                alert("上传失败！");
            }

        }

        //上传失败
        function uploadFailed(evt) {
            alert("上传失败！");
        }

        //生成随机数
        function randomNum (minNum, maxNum) {
            switch (arguments.length) {
                case 1:
                    return parseInt(Math.random() * minNum + 1, 10)
                case 2:
                    return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
                default:
                    return 0
            }
        }

    })
</script>
</html>
